using Backoffice.Domain.Repositories;
using Backoffice.Domain.Entities.App;
using Backoffice.Application.Common.Interfaces;

namespace Backoffice.Application.Services;

public class DataFixService
{
    private readonly IRepository<AppUser> _userRepo;
    private readonly IPasswordHasher _passwordHasher;

    public DataFixService(IRepository<AppUser> userRepo, IPasswordHasher passwordHasher)
    {
        _userRepo = userRepo;
        _passwordHasher = passwordHasher;
    }

    /// <summary>
    /// 修复数据库中的密码哈希问题
    /// </summary>
    public async Task<bool> FixPasswordHashesAsync()
    {
        try
        {
            var users = await _userRepo.GetAllAsync();
            var fixedCount = 0;

            foreach (var user in users)
            {
                // 检查是否是旧的明文密码哈希
                if (user.PasswordHash == "113" || !user.PasswordHash.StartsWith("$2a$"))
                {
                    // 为admin用户设置默认密码"password"
                    string newPassword = user.Username == "admin" ? "password" : "123456";
                    string newHash = _passwordHasher.HashPassword(newPassword);
                    
                    user.ChangePassword(newHash);
                    await _userRepo.UpdateAsync(user);
                    fixedCount++;
                }
            }

            return fixedCount > 0;
        }
        catch (Exception ex)
        {
            // 记录错误但不抛出异常
            Console.WriteLine($"修复密码哈希时出错: {ex.Message}");
            return false;
        }
    }
} 